package com.xw.kotlinlib.network;

import com.google.gson.JsonSyntaxException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.HttpException;

public class NetDataUtil {

    /**
     * 将传入的异常转化成友好的提示并返回.
     *
     * @param throwable 异常
     * @return 需要显示的提示
     */
    public static String getMessage(Throwable throwable) {
        String message;
        if (throwable instanceof HttpException) {
            int errorCode = ((HttpException) throwable).code();
            message = "网络异常:" + errorCode;
        } else if (throwable instanceof DataException) {
            message = ((DataException) throwable).getErrorMsg();
        } else if (throwable instanceof SocketTimeoutException) {
            message = "连接超时";
        } else if (throwable instanceof ConnectException) {
            message = "连接失败";
        } else if (throwable instanceof JsonSyntaxException || throwable instanceof UnsupportedOperationException) {
            message = "数据解析异常";
        } else if (throwable instanceof UnknownHostException) {
            message = "暂无网络";
        } else {
            message = throwable.getMessage();
        }
        return message;
    }

    public static String getMessage(TResult.Error error) {
        Throwable throwable = null;
        if (error != null) {
            throwable = error.getException();
        }
        return getMessage(throwable);
    }

    /**
     * 返回错误码
     *
     * @param throwable 网络异常类型
     * @return 接口定义的错误码
     */
    public static int getErrorCode(Throwable throwable) {
        int code = -1;
        if (throwable instanceof HttpException) {
            code = ((HttpException) throwable).code();
        } else if (throwable instanceof DataException) {
            code = ((DataException) throwable).getErrorCode();
        }
        return code;
    }

    public static int getErrorCode(TResult.Error error) {
        Throwable throwable = null;
        if (error != null) {
            throwable = error.getException();
        }
        return getErrorCode(throwable);
    }

}
